﻿using System.Web;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public class WebCacheProvider : ICacheProvider {
		private HttpContext m_context;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public object this[string key] {
			get {
				System.Diagnostics.Debug.Assert(m_context != null);

				return m_context.Cache.Get(key);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		public System.Collections.IEnumerator GetEnumerator() {
			return m_context.Cache.GetEnumerator();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		public WebCacheProvider(HttpContext context) {
			System.Diagnostics.Debug.Assert(context != null);

			m_context = context;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public void Add(string key, object value) {
			Add(key, value, null);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		/// <param name="dependencyFile"></param>
		public void Add(string key, object value, string dependencyFile) {
			System.Diagnostics.Debug.Assert(m_context != null);

			m_context.Cache.Remove(key);

			if (value == null) {
				return;
			}

			m_context.Cache.Insert(
				key,
				value,
				dependencyFile == null || dependencyFile.Length == 0 ? null : new System.Web.Caching.CacheDependency(dependencyFile),
				System.Web.Caching.Cache.NoAbsoluteExpiration,
				System.Web.Caching.Cache.NoSlidingExpiration,
				System.Web.Caching.CacheItemPriority.Default,
				null);
		}
	} // end of WebCacheProvider.
}
